import React from 'react';
import _ from 'lodash';
import Title from '../_/title';
import redux from '../_/redux';
import _name, {_title} from './dev';
import {context} from '../_';

import tinymce from '../../libs/tinymce';
const tpls = require.context('./tpl');
const tplContainer = tpls('./container.html');

@context('params')
@redux(_name, {
    data: '_',
    parser: (state, get, {params: {id}}) => _.find(state, (v) => v.Id === id),
    loadArgs: ({params: {id}}) => ({id, _fs: '*'}),
    actions: ['modify', 'load']
})

export default class Design extends React.Component {
    componentDidMount() {
        tinymce.printCheck();
        tinymce.init();
        tinymce.set({
            header: tpls('./footer.html'),
            main: tpls('./main.html'),
            footer: tpls('./footer.html')
        });
    }

    componentWillReceiveProps(props) {
        const {data} = props;
        const {data: rawdata} = this.props;
        if (data !== rawdata) {
            this.setState({errMsg: false});
            if (data.Content) {
                const content = JSON.parse(data.Content);
                if (content && content.main) {
                    tinymce.set(content);
                }
            }
        }
    }

    onState = (flag) => {
        switch (flag) {
        case 'new': {
            const {params: {id}} = this.props;
            const Content = tinymce.get();
            this.props.modify({Id: id, Content});
            break;
        }
        }
    }

    render() {
        return (
            <div className="w100">
                <Title
                    onState={this.onState}
                    title={`${_title}编辑`}
                    btn2Text="保存"
                />
                {/*eslint 'react/no-danger':0*/}
                <div dangerouslySetInnerHTML={{__html: tplContainer}}/>
                <div id="printWrapper"/>
            </div>
        );
    }
}

